import {BaseUrl} from "../constant/constant";
import {ApiFetch} from "../api/apiHandler";

class MallModel {
    constructor() {
        this.url = BaseUrl
    }

    all = (params) => {
        let end = this.url + 'getgoods'
        let req = new ApiFetch(end)
        return req.fetch(params)
    }

    get = (params) => {
        let end = this.url + 'getgoodsbyid'
        let req = new ApiFetch(end)
        return req.fetch(params)
    }

    delete = (params) => {
        let end = this.url + 'delgoodsbyidht'
        let req = new ApiFetch(end)
        return req.fetch(params)
    }

    add = (params) => {
        let end = this.url + 'addgoodsht'
        let fm = new FormData()
        const data = [{...params,}]
        if (params.imgs) {
            data[0].Imgs = []
            params.imgs.map(img => {
                if (typeof img === 'string') {
                    data[0].Imgs.push(img)
                } else {
                    data[0].Imgs.push(img.name)
                    fm.append(img.name, img.originFileObj)
                }
            })
        }
        if (params.detailImgs) {
            data[0].Detailimgs = []
            params.detailImgs.map(img => {
                if (typeof img === 'string') {
                    data[0].Detailimgs.push(img)
                } else {
                    data[0].Detailimgs.push(img.name)
                    fm.append(img.name, img.originFileObj)
                }
            })
        }

        fm.append('Data', JSON.stringify(data))
        // Object.entries(params).map(([key, value]) => {
        //     if (value !== undefined && value !== null) {
        //         if (key === 'Imgs' || key === 'Detailimgs') {
        //             const imgs = []
        //             value.map(img => {
        //                 if (typeof img === 'string') {
        //                     imgs.push(img)
        //                 } else {
        //                     imgs.push(img.name)
        //                     fm.append(img.name, img.originFileObj)
        //                 }
        //             })
        //             fm.append(key, JSON.stringify(imgs))
        //         } else {
        //             fm.append(key, JSON.stringify(value))
        //         }
        //     }
        //
        // })
        let req = new ApiFetch(end)
        return req.fetch(fm)
    }
}

export default MallModel